package com.campus.server.dao;

import com.campus.common.vo.User;
import com.campus.common.util.DBUtil;

import java.sql.*;
import java.util.*;

public class UserDao {
    public boolean isLogin(String username, String password, String role) {
        try (Connection conn = DBUtil.getConnection(); //从DBUtil获取数据库连接
             Statement st = conn.createStatement(); //创建Statement对象用于执行SQL
             ResultSet rs = st.executeQuery("SELECT * FROM user1")) { //执行查询，返回结果集
            //遍历结果集的每一行
            while (rs.next()) {
                if (rs.getString("username").equals(username) && rs.getString("password").equals(password)) {
                    if (rs.getString("role").equals(role)) {
                        return true;
                    }
                }
            }
        } catch (Exception e) { e.printStackTrace(); }
        return false;
    }

    public boolean isChange(String username,String password){
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(
                     "UPDATE user1 SET password = ? WHERE username = ?")) {
            conn.setAutoCommit(true);  // 确保立即提交
            ps.setString(1, password);
            ps.setString(2, username);
            int rows = ps.executeUpdate();
            System.out.println("更新行数: " + rows); // 调试用
            return rows > 0;
        } catch (Exception e) { e.printStackTrace(); }
        return false;
    }
    public String getUserRole(String username) {
        String role = "";
        String sql = "SELECT role FROM user1 WHERE username = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, username);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                role = rs.getString("role");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return role;
    }
}
